# -*- coding:utf-8 -*-
"""
表单
参数
请求头
"""
# 有道词典翻译逆向

import requests
import execjs
import hashlib
import time
import json


class TransData(object):
    def __init__(self):
        self.name = input("请输入需要翻译的内容：")
        self.url = "https://dict.youdao.com/webtranslate"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
            'Cookie': 'OUTFOX_SEARCH_USER_ID_NCOO=1011103432.6005298; OUTFOX_SEARCH_USER_ID=-649379569@39.128.83.81',
            'Host': 'dict.youdao.com',
            'Origin': 'https://fanyi.youdao.com',
            'Pragma': 'no-cache',
            'Referer': 'https://fanyi.youdao.com/'
        }

    def get_data_index(self):
        time_type = int(time.time() * 1000)
        content = f'client=fanyideskweb&mysticTime={time_type}&product=webfanyi&key=fsdsogkndfokasodnaso'

        # 对时间戳，进行md5加密，并转化为16进制
        sign = hashlib.md5(content.encode(encoding="utf-8")).hexdigest()
        data = {
            'i': self.name,
            'from': 'auto',
            'to': '',
            'dictResult': 'true',
            'keyid': 'webfanyi',
            'sign': sign,
            'client': 'fanyideskweb',
            'product': 'webfanyi',
            'appVersion': '1.0.0',
            'vendor': 'web',
            'pointParam': 'client,mysticTime,product',
            'mysticTime': time_type,
            'keyfrom': 'fanyi.web',
        }
        response = requests.post(self.url, data=data, headers=self.headers).text
        content = open("trans.js", "r", encoding="utf-8").read()
        data_js = execjs.compile(content, cwd=r"C:\Users\34957\AppData\Roaming\npm\node_modules")
        response_new = data_js.call("translate", response)
        data = json.loads(response_new)["translateResult"][0][0]["tgt"]
        print(data)


if __name__ == '__main__':
    trans = TransData()
    trans.get_data_index()
